<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <el-form label-width="100px" size="small">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
<!--            <el-form-item label="商品名称">-->
<!--              <zSelect  collapseTags  :value.sync="query.goodsIds" valueKey="goodsId"-->
<!--                       labelKey="goodsName" url="/api/dropDown/basGoodsListForAdd"/>-->
<!--            </el-form-item>-->
            <el-form-item label="商品名称">
              <table-select
                :tableColumns="[{prop:'goodsCode',label:'商品编码',width:'100'},{prop:'goodsName',label:'商品名称',width: '280'}]"
                labelKey="goodsName"
                valueKey="goodsId"
                :value.sync="query.goodsIds"
                placeholder="请选择商品"
                url="/api/dropDown/basGoodsListForAdd"
              ></table-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
<!--            <el-form-item label="商品类型">-->
<!--              <zSelect collapseTags  :value.sync="query.goodsTagIds" url="api/dropDown/basGoodsTagList" style="width: 100%;"/>-->
<!--            </el-form-item>-->
            <el-form-item label="商品类型">
              <!--                  <zSelect multiple :value.sync="goodsTagList"  url="/api/dropDown/basGoodsTagList"-->
              <!--                           style="width:  100%;"/>-->
              <table-select
                :tableColumns="[{prop:'name',label:'商品类型',width:350}]"
                :value.sync="query.goodsTagIds"
                placeholder="请选择分类"
                url="/api/dropDown/basGoodsTagList"
              ></table-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="商品分类">
              <treeselect
                multiple
                v-model="goodsTypeIds"
                :options="typeList"
                placeholder="选择商品分类"
                style="width: 100%"
                :normalizer="normalizer"
                @input="getgoodsType"
              >
              </treeselect>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
<!--            <el-form-item label="商品品牌">-->
<!--              <zSelect collapseTags   :value.sync="query.goodsBrandId" url="api/dropDown/basGoodsBrandList" style="width:  100%;">-->
<!--              </zSelect>-->
<!--            </el-form-item>-->
            <el-form-item label="商品品牌">
              <table-select
                :tableColumns="[{prop:'code',label:'品牌编码',width:'100'},{prop:'name',label:'品牌名称',width: '280'}]"
                :value.sync="query.goodsBrandIds"
                placeholder="请选择品牌"
                url="/api/dropDown/basGoodsBrandList"
              ></table-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-button class="filter-item"  size="mini" type="primary" @click="queryReport">搜索</el-button>
      <el-button class="filter-item" plain   size="mini" type="primary"
                 @click="resetQuery" >重置</el-button>
      <crudOperation :permission="permission">
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="40%" >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-row>
           <el-col :span="24">
             <el-form-item label="商品">
               <zSelect
                 :value.sync="form.goodsId"
                 :showName="form.goodsName"
                 valueKey="goodsId"
                 labelKey="goodsName"
                 url="/api/dropDown/basGoodsListForAdd"
                 @change="upgoods"></zSelect>
             </el-form-item>
           </el-col>
          </el-row>
          <el-row type="flex">
              <el-col>
                <el-form-item label="编码">
                  <el-input v-model="form.goodsCode" disabled leadonly />
                </el-form-item>
                <el-form-item label="含税单价">
                  <el-input v-model="form.taxPrice"  @change="changePrice('taxPrice')"/>
                </el-form-item>
                <el-form-item label="含税箱价">
                  <el-input v-model="form.taxBoxPrice"  @change="changePrice('taxBoxPrice')" />
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="规格型号">
                  <el-input v-model="form.model" disabled leadonly />
                </el-form-item>
                <el-form-item label="未税单价">
                  <el-input v-model="form.noTaxPrice"  disabled leadonly  />
                </el-form-item>
                <el-form-item label="未税箱价">
                  <el-input v-model="form.noTaxBoxPrice"  disabled leadonly  />
                </el-form-item>
              </el-col>
          </el-row>
          <el-form-item label="备注">
            <el-input v-model="form.remark"  />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="submit">确认</el-button>
        </div>
      </el-dialog>

      <vue-context-menu :contextMenuData="contextMenuData"
                        @tableConfig="tableConfig"
                        @deletedata="deletedata"></vue-context-menu>
      <!-- 表格配置 -->
      <el-dialog title="表格配置"
                 :visible.sync="tableConfigShow"
                 width="60%">
        <j-table-column-config :columns.sync="crud.header"  @tabSave="tabSave" @pit="pit" />
      </el-dialog>

      <!--表格渲染-->
      <el-table ref="table"
                stripe
                @cell-dblclick="row=>crud.toEdit(row)"
                border v-loading="crud.loading"
                :data="crud.data" size="small"
                style="width: 100%;"
                @selection-change="crud.selectionChangeHandler"
                v-if="isShowTable"
                @header-dragend="changeColWidth"
                @contextmenu.native="showMenu"
                highlight-current-row="highlight-current-row"
                @row-dblclick="switchRowIndex">
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60" />
        <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
        <el-table-column
          v-if="item.visible"
          v-for="(item, index) in crud.header"
          :key="`col_${index}`"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          :data-porp='item.prop'
          @contextmenu.native="showMenu"
          @header-dragend="changeColWidth"
        >
          <!-- 自定义渲染模版 -->
          <template slot-scope="scope">
            <!-- 当列key为 sort 时，渲染一个手柄icon -->
            <template v-if="item.prop =='sort'">
              <div class="handle_move">
                <i :class="scope.row['sort']" />
              </div>
            </template>
            <template v-else>
              <span v-if="item.type == 1" style="margin-left: 0px">{{scope.row[`${item.prop}`]}}</span>
              <span v-if="item.type == 2" style="margin-left: 0px">{{ parseTime(scope.row[`${item.prop}`])}}</span>
              <span v-if="item.type == 3" style="margin-left: 0px">{{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}</span>
              <span v-if="item.type == 4" style="margin-left: 10px">
                <template slot-scope="scope">
                  <span v-if="item.prop === 'goodsName'">
                    <span v-if="scope.$index === rowIndex">{{ scope.row.goodsName }}</span>
                  </span>
                </template>
              </span>
            </template>
          </template>
        </el-table-column>
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('id')" prop="id" label="id" />-->
<!--&lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('orderId')" prop="orderId" label="价格套id" />&ndash;&gt;-->
<!--&lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsId')" prop="goodsId" label="商品id" />&ndash;&gt;-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCode')" prop="goodsCode" label="商品编码" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsName')" prop="goodsName" label="商品名称" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('barcode')" prop="barcode" label="条形码" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('boxBarcode')" prop="boxBarcode" label="箱装条形码" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('helpSign')" prop="helpSign" label="助记符" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('model')" prop="model" label="规格型号" />-->
<!--&lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsBrandId')" prop="goodsBrandId" label="商品品牌id" />&ndash;&gt;-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsBrandCode')" prop="goodsBrandCode" label="商品品牌编码" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsBrandName')" prop="goodsBrandName" label="商品品牌名称" />-->
<!--&lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsTypeId')" prop="goodsTypeId" label="商品分类id" />&ndash;&gt;-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsTypeCode')" prop="goodsTypeCode" label="商品分类编码" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsTypeName')" prop="goodsTypeName" label="商品分类名称" />-->
<!--&lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsTagId')" prop="goodsTagId" label="商品类型id" />&ndash;&gt;-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsTagCode')" prop="goodsTagCode" label="商品类型编码" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsTagName')" prop="goodsTagName" label="商品类型名称" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxPrice')" prop="taxPrice" label="含税单价" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('noTaxPrice')" prop="noTaxPrice" label="未税单价" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxBoxPrice')" prop="taxBoxPrice" label="含税箱价" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('noTaxBoxPrice')" prop="noTaxBoxPrice" label="未税箱价" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('seq')" prop="seq" label="排序" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注" />-->
<!--&lt;!&ndash;        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('createUserId')" prop="createUserId" label="添加人id" />&ndash;&gt;-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('createUserCode')" prop="createUserCode" label="添加人编码" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('createUserName')" prop="createUserName" label="添加人名称" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('createTime')" prop="createTime" label="添加时间">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.createTime) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('updateUserId')" prop="updateUserId" label="修改人id" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('updateUserCode')" prop="updateUserCode" label="修改人编码" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('updateUserName')" prop="updateUserName" label="修改人名称" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('updateTime')" prop="updateTime" label="修改时间">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.updateTime) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column :render-header="crud.renderHeader" v-permission="['admin','basGoodsPriceSuitDetail:edit','basGoodsPriceSuitDetail:del']" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudBasGoodsPriceSuitDetail from '@/api/erp/basGoodsPriceSuitDetail'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import Treeselect from '@riophae/vue-treeselect'
import {getTypeList} from "@/api/erp/basGoodsType";
import { get } from '@/api/erp/basGoodsPriceSuitDetail'
import {salesDetailKey} from "@/utils/key";
import { publicListKey } from "@/utils/key";
import {getHeaderProperties} from "@/api/erp/headerProperties";
import {tablemixins} from "@/mixins/tablemixins";
import  jTableColumnConfig  from "@/components/jTableColumnConfig/jTableColumnConfig";


// crud交由presenter持有
const defaultCrud = CRUD({ title: '商品价格套明细',
  optShow: {
    add: true,
    edit: true,
    del: true,
    download: true,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: false,
    reject: false,
    invalid: false,
    recover: false,
    downloadDetail: false,
    print: false,
    printDetail: false,
  },
  url: '/api/basGoodsPriceSuit/detail',
  sort: 'id,desc',
  params() {
    return {
      orderId: location.href.match(/\/\d+$/)[0].split("/")[1]
    }
  },
  crudMethod: { ...crudBasGoodsPriceSuitDetail }})
const defaultForm = {
  id: null,
  orderId: null,
  goodsId: null,
  goodsCode: null,
  goodsName: null,
  barcode: null,
  boxBarcode: null,
  helpSign: null, model: null,thirdUnitCount:null,goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null}
export default {
  name: 'basGoodsPriceSuitDetail',
  components: { pagination, crudOperation, rrOperation, udOperation, Treeselect ,jTableColumnConfig},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(),publicListKey,tablemixins,salesDetailKey],
  created() {
      this.query.orderId = location.href.match(/\/\d+$/)[0].split("/")[1]
      this.form.orderId = location.href.match(/\/\d+$/)[0].split("/")[1]
      this.getTypeList()
      console.log(this.query.id)
  },
  activated() {
    //获取上次进入Id
    const id = sessionStorage.getItem(this.$options.name + 'Id')
    //记录本次进入的Id
    sessionStorage.setItem(this.$options.name + 'Id', this.$route.params.id)
    // if (!this.crud.header) this.getHeader()
    if (id !== this.$route.params.id) {
      this.query.orderId = location.href.match(/\/\d+$/)[0].split("/")[1]
      this.form.orderId = location.href.match(/\/\d+$/)[0].split("/")[1]
      this.resetQuery()
    }
  },
  data() {
    return {
      goodsIds:[],
      goodsBrandId:[],
      goodsTypeIds:[],
      goodsTagIds:[],
      // goodsTypeId:[],
      typeList:[],
      permission: {
        add: ['admin', 'basGoodsPriceSuit:add'],
        edit: ['admin', 'basGoodsPriceSuit:edit'],
        del: ['admin', 'basGoodsPriceSuit:del'],
        import: ['admin', 'basGoodsPriceSuit:import'],
        export: ['admin', 'basGoodsPriceSuit:export'],
        copy: ['admin', 'basGoodsPriceSuit:copy'],
        upload: ['admin', 'basGoodsPriceSuit:upload'],
        download: ['admin', 'basGoodsPriceSuit:download'],
      },
      rules: {
        orderId: [
          { required: true, message: '价格套id不能为空', trigger: 'blur' }
        ],
        goodsId: [
          { required: true, message: '商品id不能为空', trigger: 'blur' }
        ]
      },


      taxName:null,
      taxRate:0,
      goodsId:null
    }
  },
  watch:{
    // goodsTypeIds(n){
    //   this.$set(this.query,'goodsTypeIds',n.join(',') || '')
    // }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })},
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    init(){
      this.page = 1
      // this.crud.data = []
    },
    getgoodsType(val){
      let str = ''
      val.forEach(item=>{
        const itemNode = this.getTreeName(this.typeList,item)
        str = this.getNode(itemNode,str)
      })
      this.query.goodsTypeIds = str
      console.log(this.query.goodsTypeIds)
    },
    getTreeName(treeList,id){
      let _this=this
      for (let i = 0; i < treeList.length; i++) {
        let treeItem=treeList[i]
        if(treeItem.id===id){
          return treeItem
        }else{
          if(treeItem.children && treeItem.children.length>0){
            let res=_this.getTreeName(treeItem.children,id)
            if(res){
              return res
            }
          }
        }
      }
    },
    getNode(node,str){
      if (node.children){
        for (let i =0;i<node.children.length;i++){
          str = this.getNode(node.children[i],str)
        }
      }
      return str+=node.id+ ','
    },
    submit(){
      this.form.orderId=location.href.match(/\/\d+$/)[0].split("/")[1]
      this.crud.submitCU()
    },
    changePrice(type){
      console.log(type)
     if (type === 'taxPrice'){
       this.form.noTaxPrice = (this.form.taxPrice/(1+this.taxRate/100)).toFixed(2)
       this.form.taxBoxPrice = (this.form.taxPrice*this.form.boxUnitCount).toFixed(2)
       this.form.noTaxBoxPrice = (this.form.taxBoxPrice/(1+this.taxRate/100)).toFixed(2)
     }else if (type === 'taxBoxPrice'){
       this.form.taxPrice = (this.form.taxBoxPrice/this.form.boxUnitCount).toFixed(2)
       this.form.noTaxPrice = (this.form.taxPrice/(1+this.taxRate/100)).toFixed(2)
       this.form.noTaxBoxPrice = (this.form.taxBoxPrice/(1+this.taxRate/100)).toFixed(2)
     }
   },
    getTypeList() {
      getTypeList({page: 0, size: 999}).then(res => {
        this.typeList = res
      })

    },
    resetQuery() {
      // this.query = {
        // goodsIds:null,
        // goodsTagIds:null,
        // goodsTypeId:null,
        // goodsBrandId:null,
        // goodsTypeIds:null,
        // page: 1,
        // size: 10,
      // }
      this.goodsIds = []
      this.goodsTagIds = []
      this.goodsTypeIds = []
      this.goodsBrandId = []
      this.crud.resetQuery()

    },
    queryReport(){
      this.init()
      this.crud.toQuery()
    },

    // onGet(){
    //   // this.init()
    //   // this.query.goodsTypeIds = this.goodsTypeId.toString()
    //   console.log(this.query.goodsTypeIds)
    //   // this.query.goodsTypeIds = this.goodsTypeId.length?this.goodsTypeId.join(','):''
    //   // this.init()
    //   // console.log(this.query.goodsTypeIds)
    //   // const that =this
    //   // get({...this.query,...this.crud.page}).then(res=>{
    //   //   that.crud.data = res.data.content
    //   //   that.crud.page.total = res.data.totalElements
    //   // })
    // },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    upgoods(val){
      this.form.goodsCode = val.goodsCode
      this.form.model = val.model
      this.form.goodsTypeName = val.goodsTypeName
      this.form.boxUnitCount = val.boxUnitCount

      this.taxRate = val.taxRate
      this.taxName = val.taxName
    },
  }
}
</script>

<style scoped>
  .table-img {
    display: inline-block;
    text-align: center;
    background: #ccc;
    color: #fff;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    width: 32px;
    height: 32px;
    line-height: 32px;
  }
</style>
